package com.chensf.studydemo.common;


import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.Xfermode;
import android.util.AttributeSet;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;

import static android.graphics.BlendMode.DST_IN;

/**
 * 通过 Path 将内容 views 切割成任意形状.
 *
 * @author Heycz
 */
public abstract class ShapeLayout extends FrameLayout {

    private static final String TAG = "ShapeLayout";

    private final Matrix mMatrix = new Matrix();
    private final Path mPath = new Path();
    protected boolean disableShape = false;
    private final Paint mPaint = new Paint();

    public ShapeLayout(Context context) {
        this(context, null);
    }

    public ShapeLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ShapeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mPaint.setAntiAlias(true);
    }

    protected abstract void drawPath(Path path, int srcWidth, int srcHeight, float scale,
                                     float translateX, float translateY);

    protected void calculateSrcSize() {
        int srcWidth = getWidth();
        int srcHeight = getHeight();

        if (srcWidth > 0 && srcHeight > 0) {
            float width = getWidth();
            float height = getHeight();

            float scale;
            float translateX = 0;
            float translateY = 0;

            if (srcWidth * height > width * srcHeight) {
                scale = height / srcHeight;
                translateX = Math.round((width / scale - srcWidth) / 2f);
            } else {
                scale = width / (float) srcWidth;
                translateY = Math.round((height / scale - srcHeight) / 2f);
            }

            mMatrix.setScale(scale, scale);
            mMatrix.preTranslate(translateX, translateY);
            mMatrix.postTranslate(0, 0);

            drawPath(mPath, srcWidth, srcHeight, scale, translateX, translateY);
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        calculateSrcSize();
    }

    @Override
    public void draw(Canvas canvas) {
        if (!disableShape && getBackground() != null) {
            canvas.clipPath(mPath);
        }
        super.draw(canvas);
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        if (!disableShape) {
            canvas.clipPath(mPath);
        }
        super.dispatchDraw(canvas);
    }

    public void setDisableShape(boolean disable) {
        this.disableShape = disable;
    }

}